package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.Result;
import com.example.demo.common.ErrorCode;
import com.example.demo.service.ZhipuAIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ContentDisposition;
import java.nio.charset.StandardCharsets;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/assessment")
public class AssessmentController {

    @Autowired
    private ZhipuAIService zhipuAIService;

    /**
     * 生成测评问题
     */
    @PostMapping("/generate-question")
    public Result generateQuestion(@RequestBody(required = false) List<Map<String, String>> previousQA) {
        try {
            String questionJson = zhipuAIService.generateQuestion(previousQA);
            return Result.success(JSON.parseObject(questionJson));
        } catch (Exception e) {
            log.error("生成问题失败", e);
            return Result.error(ErrorCode.OPERATION_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 生成分析报告
     */
    @PostMapping("/generate-analysis")
    public Result generateAnalysis(@RequestBody List<Map<String, String>> qaRecords) {
        try {
            String analysisJson = zhipuAIService.generateAnalysis(qaRecords);
            return Result.success(JSON.parseObject(analysisJson));
        } catch (Exception e) {
            log.error("生成分析报告失败", e);
            return Result.error(ErrorCode.OPERATION_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 下载分析报告
     */
    @PostMapping("/download-report")
    public ResponseEntity<byte[]> downloadReport(@RequestBody Map<String, Object> reportData) {
        try {
            byte[] reportContent = zhipuAIService.generateReportFile(reportData);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDisposition(ContentDisposition.builder("attachment")
                .filename("儿童心理测评报告.pdf", StandardCharsets.UTF_8)
                .build());
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);
            
            return ResponseEntity.ok()
                .headers(headers)
                .body(reportContent);
        } catch (Exception e) {
            log.error("生成报告文件失败", e);
            throw new RuntimeException("生成报告文件失败: " + e.getMessage());
        }
    }
} 